<?php
class Pageley_Domain_BasicFileManager implements Pageley_Domain_FileManager {
    
    private $directory;
    private $contextPath;
    private $mimeTypeMapping;
    
    public function __construct($directory, $contextPath, $mimeTypeMapping = null) {
        $this->directory = $directory;
        $this->contextPath = $contextPath;
        if($mimeTypeMapping === null) {
            $mimeTypeMapping = new Pageley_Util_ArrayMap();
            $mimeTypeMapping->put("txt", "text/plain");
            $mimeTypeMapping->put("htm", "text/html");
            $mimeTypeMapping->put("html", "text/html");
            $mimeTypeMapping->put("css", "text/css");
            $mimeTypeMapping->put("js", "application/javascript");
            $mimeTypeMapping->put("xml", "application/xml");
            $mimeTypeMapping->put("zip", "application/zip");
            $mimeTypeMapping->put("gif", "image/gif");
            $mimeTypeMapping->put("jpg", "image/jpeg");
            $mimeTypeMapping->put("png", "image/png");
            $mimeTypeMapping->put("*", "application/octet-stream");
        }
        $this->mimeTypeMapping = $mimeTypeMapping;
    }
    
    public function getDirectory() {
        return $this->directory;
    }
    
    public function getContextPath() {
        return $this->contextPath;
    }
    
    public function deriveMimeType($extension) {
        $mimeType = $this->mimeTypeMapping->get($extension);
        if($mimeType === null) {
            $mimeType = $this->mimeTypeMapping->get("*");
        }
        return $mimeType;
    }
    
    public function resolveLocation($file) {
        $path = $file->getPath();
        if(!Pageley_Util_String::startsWith($path, $this->directory)) {
            throw new Pageley_Util_NestedRuntimeException("File '" . $file . "' is not located within '" . $this->directory . "'.");
        }
        return Pageley_Util_String::substringAfter($path, $this->directory);
    }
}